package com.gold.controller;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.gold.entity.AdminUser;
import com.gold.entity.Card;
import com.gold.entity.Expense;
import com.gold.entity.Game;
import com.gold.entity.GameType;
import com.gold.entity.Mobile;
import com.gold.entity.Prepaid;
import com.gold.entity.ResultMsg;
import com.gold.entity.Status;
import com.gold.entity.User;
import com.gold.myexception.Myexception;
import com.gold.service.CardService;
import com.gold.service.ExpenseService;
import com.gold.service.GameService;
import com.gold.service.GameTypeService;
import com.gold.service.MobileService;
import com.gold.service.PrepaidService;
import com.gold.service.StatusService;
import com.gold.service.UserService;
import com.gold.util.Myutil;

@Controller
public class UserController {

	private Logger log = Logger.getLogger(this.getClass());

	@Autowired
	private UserService us;
	@Autowired
	private GameTypeService gts;
	@Autowired
	private GameService gs;
	@Autowired
	private StatusService ss;
	@Autowired
	private MobileService ms;
	@Autowired
	private PrepaidService ps;
	@Autowired
	private CardService cs;
	@Autowired
	private ExpenseService es;

	@RequestMapping("getAllUserByPage")
	public String getAllUserByPage(String nowPageString, ModelMap mm, HttpServletRequest request) {
		AdminUser oldau = (AdminUser) request.getSession().getAttribute("adminLoginUser");
		if (oldau == null) {
			return "redirect:gold/index.jsp";
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("nowPageString", nowPageString);
		List<User> userList = us.selectUserByPage(map);
		mm.addAttribute("userList", userList);
		mm.addAttribute("nowPage", map.get("nowPageString"));
		return "/gold/user/user.jsp";
	}

	@RequestMapping("getUserByLikeAndPage")
	public String getUserByLikeAndPage(String userName, String userPhone, String nowPageString, ModelMap mm) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("nowPageString", nowPageString);
		map.put("userName", userName);
		map.put("userPhone", userPhone);
		List<User> userList = us.selectUserByLikeAndPage(map);
		mm.addAttribute("userList", userList);
		mm.addAttribute("nowPage", map.get("nowPageString"));
		return "/gold/user/user.jsp";
	}

	@RequestMapping("updateUserStatusIdByUserId")
	public String updateUserStatusIdByUserId(String[] arr, String status) {
		if (arr != null && status != null) {
			if (arr.length >= 1) {
				us.updateUserStatusIdByUserId(arr, status);
			}
		}
		return "getAllUserByPage.do";
	}

	@RequestMapping("getAllUser")
	@ResponseBody
	public ResultMsg getAllUser(String userName) {
		if (!Myutil.checkStringNull(userName)) {
			return new ResultMsg(false, "用户名不合法");
		}
		User user = us.selectUserByUserName(userName);
		if (user != null) {
			if (user.getUserStatusId() == 2) {
				return new ResultMsg(false, "用户已被禁用");
			}
			return new ResultMsg(true, "请输入密码");
		} else {
			return new ResultMsg(false, "用户不存在");
		}
	}

	@RequestMapping("userLogin")
	public ModelAndView userLogin(String userName, String userPwd, HttpServletRequest request) {
		log.info("userLogin");
		ModelAndView mm = new ModelAndView();
		if (Myutil.checkStringNull(userName, userPwd)) {
			try {
				User user = us.userLogin(userName, userPwd);
				request.getSession().setAttribute("userLogin", user);
				List<GameType> gameTypeList = gts.selectAllGameTypeByPortal();
				List<GameType> gameTypePortalList = gts.selectGameTypeByPortal();
				List<GameType> gameTypePortalMoreList = gts.selectGameTypeByPortalMore();
				List<Game> gameList = gs.selectGameByPortal();
				request.getSession().setAttribute("gameList", gameList);
				request.getSession().setAttribute("gameTypePortalList", gameTypePortalList);
				request.getSession().setAttribute("gameTypeList", gameTypeList);
				request.getSession().setAttribute("gameTypePortalMoreList", gameTypePortalMoreList);
				mm.setViewName("redirect:/gold/user/portal.jsp");
				return mm;
			} catch (Myexception e) {
				mm.addObject("msg", e.getMessage());
			}
		} else {
			mm.addObject("msg", "用户名或密码不合法");
		}
		mm.setViewName("/gold/user/login.jsp");
		return mm;
	}

	@RequestMapping("guestLogin")
	public ModelAndView guestLogin(HttpServletRequest request) {
		ModelAndView mm = new ModelAndView();
		List<GameType> gameTypeList = gts.selectAllGameType();
		List<GameType> gameTypePortalList = gts.selectGameTypeByPortal();
		List<GameType> gameTypePortalMoreList = gts.selectGameTypeByPortalMore();
		List<Game> gameList = gs.selectGameByPortal();
		request.getSession().setAttribute("guestLogin", "guestLogin");
		request.getSession().setAttribute("gameList", gameList);
		request.getSession().setAttribute("gameTypePortalList", gameTypePortalList);
		request.getSession().setAttribute("gameTypeList", gameTypeList);
		request.getSession().setAttribute("gameTypePortalMoreList", gameTypePortalMoreList);
		mm.setViewName("redirect:/gold/user/portal.jsp");
		return mm;
	}

	@RequestMapping("checkUserRegisterName")
	@ResponseBody
	public ResultMsg checkUserRegisterName(String userName) {
		User user = us.selectUserByUserName(userName);
		if (user != null) {
			return new ResultMsg(false, "用户已经存在");
		}
		return new ResultMsg(true, "");
	}

	@RequestMapping("userRegister")
	public String userRegister(String userName, String userPwd, String userPwd2, String userPhone, String userSex, String userBirthday, ModelMap mm) {
		if (Myutil.checkStringNull(userName, userPwd, userPwd2, userPhone, userBirthday)) {
			if (userPwd.equals(userPwd2)) {
				User user = new User(0, userName, userPwd, userBirthday, userSex, userPhone, 0, 0, 0, 0, null, null);
				try {
					us.insertUser(user);
					mm.addAttribute("msg", "注册成功，请登陆");
				} catch (Myexception e) {
					mm.addAttribute("msg", e.getMessage());
				}
				return "/gold/user/login.jsp";
			} else {
				mm.addAttribute("msg", "密码不一致");
			}
		} else {
			mm.addAttribute("msg", "输入不合法");
		}
		return "/gold/user/register.jsp";
	}

	@RequestMapping("exitUserSystem")
	public String exitUserSystem(HttpServletRequest request) {
		request.getSession().invalidate();
		return "redirect:/gold/user/login.jsp";
	}

	@RequestMapping("toGameDetailJsp")
	public String toGameDetailJsp(String gameId, ModelMap mm) {
		List<GameType> gameTypePortalList = gts.selectGameTypeByPortal();
		List<Status> statusList = ss.selectAllExpStatus();
		Game game = gs.selectGameByGameId(Integer.parseInt(gameId));
		if (game == null) {
			return "redirect:/gold/user/portal.jsp";
		}
		mm.addAttribute("gameTypePortalList", gameTypePortalList);
		mm.addAttribute("statusList", statusList);
		mm.addAttribute("game", game);
		return "/gold/user/gameDetail.jsp";
	}

	@RequestMapping("changePwd")
	public String changePwd(String userName, String userPwd, String userPwd2, String userPhone, ModelMap mm, HttpServletRequest request) {
		if (Myutil.checkStringNull(userName, userPwd, userPwd2, userPhone)) {
			try {
				us.updateUserPwdByUserId(userName, userPwd, userPwd2, userPhone);
				mm.addAttribute("msg", "修改成功,请重新登陆");
				request.getSession().invalidate();
				return "/gold/user/login.jsp";
			} catch (Myexception e) {
				mm.addAttribute("msg", e.getMessage());
			}
		} else {
			mm.addAttribute("msg", "输入不合法");
		}
		return "/gold/user/forgetPwd.jsp";
	}

	@RequestMapping("addCardAmount")
	public String addCardAmount(String userIdString, String cardNumber, String cardPwd, ModelMap mm) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("userIdString", userIdString);
		map.put("cardNumber", cardNumber);
		map.put("cardPwd", cardPwd);
		if (Myutil.checkStringNull(userIdString, cardNumber, cardPwd)) {
			try {
				us.updateUserCardAmountByUserId(map);
				mm.addAttribute("msg", "充值成功");
			} catch (Myexception e) {
				mm.addAttribute("msg", e.getMessage());
			}
		} else {
			mm.addAttribute("msg", "空数据");
		}
		return "gold/user/portal.jsp";
	}

	@RequestMapping("getHotGame")
	@ResponseBody
	public void getHotGame(HttpServletRequest request) {
		List<Game> gameList = gs.selectGameByPortal();
		request.getSession().setAttribute("gameList", gameList);
	}

	@RequestMapping("toUserDetailJsp")
	public String toUserDetailJsp(ModelMap mm, HttpServletRequest request) {
		User oldUser = (User) request.getSession().getAttribute("userLogin");
		if (oldUser == null) {
			mm.addAttribute("msg", "请先登录");
			return "gold/user/login.jsp";
		}
		User newUser = us.selectUserByUserId(oldUser.getUserId());
		int MobileNumber = Integer.parseInt(newUser.getUserPhone().substring(0, 2));
		Mobile mobile = ms.selectMobileByMobileNumber(MobileNumber);
		if (mobile != null) {
			request.getSession().setAttribute("mobile", mobile);
		}
		request.getSession().setAttribute("user", newUser);
		request.getSession().setAttribute("userLogin", newUser);
		return "redirect:gold/user/userDetail.jsp";
	}

	@RequestMapping("toPrepaidJsp")
	public String toPrepaidJsp(String userIdString, ModelMap mm, HttpServletRequest request) {
		User oldUser = (User) request.getSession().getAttribute("userLogin");
		if (oldUser == null) {
			mm.addAttribute("msg", "请先登录");
			return "gold/user/login.jsp";
		}
		User newUser = us.selectUserByUserId(oldUser.getUserId());
		request.getSession().setAttribute("userLogin", newUser);
		List<Prepaid> prepaidList = ps.selectPrepaidByUserId(newUser.getUserId());
		List<Card> cardList = new LinkedList<Card>();
		for (int i = 0; i < prepaidList.size(); i++) {
			int cardId = prepaidList.get(i).getPrepCardId();
			cardList.add(cs.selectCardByCardId(cardId));
		}
		request.getSession().setAttribute("cardList", cardList);
		return "redirect:gold/user/prepaid.jsp";

	}

	@RequestMapping("toExpenseJsp")
	public String toExpenseJsp(String userIdString, ModelMap mm, HttpServletRequest request) {
		User oldUser = (User) request.getSession().getAttribute("userLogin");
		if (oldUser == null) {
			mm.addAttribute("msg", "请先登录");
			return "gold/user/login.jsp";
		}
		User newUser = us.selectUserByUserId(oldUser.getUserId());
		request.getSession().setAttribute("userLogin", newUser);
		List<Expense> expenseList = es.selectExpenseByUserId(newUser.getUserId());
		request.getSession().setAttribute("expenseList", expenseList);
		return "redirect:gold/user/expense.jsp";
	}

	@RequestMapping("buyGame")
	public Object buyGame(String gameId, String bugGameStatusId, ModelMap mm, HttpServletRequest request) {
		User oldUser = (User) request.getSession().getAttribute("userLogin");
		if (oldUser == null) {
			mm.addAttribute("msg", "请先登录");
			return "gold/user/login.jsp";
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("gameId", gameId);
		map.put("userId", oldUser.getUserId() + "");
		map.put("bugGameStatusId", bugGameStatusId);
		try {
			es.buyGame(map);
			HttpHeaders headers = new HttpHeaders();
			headers.setContentDispositionFormData("attachment", "game.txt");
			headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
			String str = "购买成功,游戏下载地址为：www.baidu.com";
			byte[] bt = str.getBytes();
			return new ResponseEntity<byte[]>(bt, headers, HttpStatus.OK);
		} catch (Myexception e) {
			mm.addAttribute("msg", e.getMessage());
		}
		return "gold/user/portal.jsp";
	}

	@RequestMapping("toGameTypeJsp")
	public String toGameTypeJsp(int gameType, HttpServletRequest request) {
		List<Game> someGameList = gs.selectGameByGameType(gameType);
		request.getSession().setAttribute("someGameList", someGameList);
		return "redirect:gold/user/gametype.jsp";
	}

	@RequestMapping("searchGame")
	public String searchGame(String gameName, String gameType, HttpServletRequest request) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("gameName", gameName);
		map.put("gameType", gameType);
		List<Game> someGameList = gs.selectGameByGameTypeAndName(map);
		request.getSession().setAttribute("someGameList", someGameList);
		return "redirect:gold/user/gametype.jsp";
	}

}
